<template>
  <div>
    <!-- 主列表页面 -->
    <div v-if="!showEditPage && !showProcessPage">
      <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
        <a-row
          class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden"
        >
          <!-- 查询条件 -->
          <a-row v-if="showSearchRow" class="w-full">
            <a-form
              :model="searchForm"
              label-align="left"
              layout="inline"
              size="small"
            >
              <a-form-item field="projectName" label="项目名称">
                <a-input
                  v-model="searchForm.projectName"
                  allow-clear
                  placeholder="请输入项目名称"
                />
              </a-form-item>
              <a-form-item field="subsidyStatus" label="补贴状态">
                <a-select
                  v-model="searchForm.subsidyStatus"
                  allow-clear
                  placeholder="请选择补贴状态"
                >
                  <a-option
                    v-for="item in dicts[DICT.lindiSubsidyApplicationStatus]"
                    :key="item.dictKey"
                    :value="item.dictKey"
                  >
                    {{ item.dictValue }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-form>
            <a-row class="w-full mt-2" justify="center">
              <a-space>
                <a-button
                  v-perm="['lindi:subsidyApplication:get']"
                  type="primary"
                  @click="search"
                >
                  <template #icon>
                    <icon-search />
                  </template>
                  <template #default>查询</template>
                </a-button>
                <a-button @click="reset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <template #default>重置</template>
                </a-button>
              </a-space>
            </a-row>
          </a-row>

          <!-- 分割线 -->
          <a-divider v-if="showSearchRow" class="mt-2" />

          <!-- 数据操作区 -->
          <a-row class="w-full flex justify-between">
            <a-space>
              <!-- 添加 -->
              <a-button
                v-perm="['lindi:subsidyApplication:add']"
                size="small"
                type="primary"
                @click="handleAdd"
              >
                <template #icon>
                  <icon-plus />
                </template>
                <template #default>新增</template>
              </a-button>
            </a-space>
            <a-space>
              <!-- 刷新 -->
              <a-button shape="circle" size="small" @click="search">
                <template #icon>
                  <icon-refresh />
                </template>
              </a-button>
              <!-- 收缩/展开 -->
              <a-button
                shape="circle"
                size="small"
                @click="showSearchRow = !showSearchRow"
              >
                <template #icon>
                  <icon-caret-up v-if="showSearchRow" />
                  <icon-caret-down v-else />
                </template>
              </a-button>
            </a-space>
          </a-row>

          <!-- 数据展示区 -->
          <a-row class="w-full flex-1 mt-3 overflow-y-auto">
            <a-table
              row-key="subsidyApplicationId"
              :loading="loading"
              :pagination="pagination"
              :columns="columns"
              :data="tableData"
              :bordered="false"
              @page-change="handlePageChange"
              @page-size-change="handlePageSizeChange"
            >
              <template #projectAddress="{ record }">
                <div class="address-cell">
                  {{ record.projectAddress }}
                </div>
              </template>
              <template #subsidyStatus="{ record }">
                <a-tag :color="getStatusColor(record.subsidyStatus)">
                  {{ getStatusText(record.subsidyStatus) }}
                </a-tag>
              </template>
              <template #operations="{ record }">
                <div
                  style="
                    display: flex;
                    flex-wrap: wrap;
                    gap: 4px;
                    justify-content: center;
                  "
                >
                  <a-button
                    v-perm="['lindi:subsidyApplication:update']"
                    type="text"
                    size="mini"
                    @click="handleEdit(record)"
                  >
                    <template #icon>
                      <icon-edit />
                    </template>
                    <template #default>修改</template>
                  </a-button>
                  <a-button
                    type="text"
                    size="mini"
                    @click="handleProcess(record)"
                  >
                    <template #icon>
                      <icon-eye />
                    </template>
                    <template #default>处理</template>
                  </a-button>
                  <a-popconfirm
                    :content="`确定删除【${record.projectName}】吗?`"
                    type="warning"
                    @ok="deleteRecord(record.subsidyApplicationId)"
                  >
                    <a-button
                      v-perm="['lindi:subsidyApplication:delete']"
                      :loading="deleteLoading"
                      size="mini"
                      status="danger"
                      type="text"
                    >
                      <template #icon>
                        <icon-delete />
                      </template>
                      <template #default>删除</template>
                    </a-button>
                  </a-popconfirm>
                </div>
              </template>
            </a-table>
          </a-row>
        </a-row>
      </a-card>
    </div>

    <!-- 编辑页面 -->
    <div v-if="showEditPage">
      <component
        :is="SubsidyEdit"
        :subsidyApplicationId="currentSubsidyId"
        @cancel="handleEditCancel"
        @ok="handleEditOk"
      />
    </div>

    <!-- 处理页面 -->
    <div v-if="showProcessPage">
      <component
        :is="SubsidyProcess"
        :subsidyApplicationId="currentSubsidyId"
        @cancel="handleProcessCancel"
        @refresh="handleProcessRefresh"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import { defineAsyncComponent } from "vue";
// 导入API方法
import {
  getPageSubsidyApplicationListApi,
  deleteSubsidyApplicationBySubsidyApplicationIdApi,
} from "~/api/lindi/subsidyApplication.js";
// 导入字典工具
import { DICT } from "~/utils/dict.js";

// 动态导入组件
const SubsidyEdit = defineAsyncComponent(() => import("./SubsidyEdit.vue"));
const SubsidyProcess = defineAsyncComponent(() =>
  import("./SubsidyProcess.vue")
);

// 全局实例
const { proxy } = getCurrentInstance();

// 加载字典数据
const dicts = proxy.LoadDicts([DICT.lindiSubsidyApplicationStatus]);

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);
const deleteLoading = ref(false);

// 搜索行显示状态
const showSearchRow = ref(true);

// 查询表单
const searchForm = reactive({
  projectName: "",
  subsidyStatus: null,
  acceptanceTimeRange: [],
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  projectName: "",
  subsidyStatus: null,
  acceptanceTimeStart: "",
  acceptanceTimeEnd: "",
});

// 分页信息
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 表格数据
const tableData = ref([]);

// 表格列
const columns = [
  {
    title: "项目名称",
    dataIndex: "projectName",
    align: "center",
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "项目地址",
    dataIndex: "projectAddress",
    align: "center",
    slotName: "projectAddress",
    width: 200,
  },
  {
    title: "补贴申领面积(亩)",
    dataIndex: "amount",
    align: "center",
  },
  {
    title: "验收时间",
    dataIndex: "acceptDate",
    align: "center",
  },
  {
    title: "申请时间",
    dataIndex: "createTime",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "subsidyStatus",
    align: "center",
    slotName: "subsidyStatus",
  },
  {
    title: "操作",
    dataIndex: "operations",
    align: "center",
    slotName: "operations",
    width: 200,
  },
];

// 编辑页面显示状态
const showEditPage = ref(false);
const showProcessPage = ref(false);
const currentSubsidyId = ref("");

// 获取状态颜色
const getStatusColor = (status) => {
  if (!status || !dicts[DICT.lindiSubsidyApplicationStatus]) {
    return "gray";
  }
  const dict = dicts[DICT.lindiSubsidyApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict?.dictClass || "gray";
};

// 获取状态文本
const getStatusText = (status) => {
  console.log("status", status);
  console.log(
    "dicts[DICT.lindiSubsidyApplicationStatus]",
    dicts[DICT.lindiSubsidyApplicationStatus]
  );
  if (!status || !dicts[DICT.lindiSubsidyApplicationStatus]) {
    return "未知状态";
  }
  const dict = dicts[DICT.lindiSubsidyApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict ? dict.dictValue : "未知状态";
};

// 加载数据
const loadData = () => {
  const queryParams = {
    current: pagination.current,
    size: pagination.pageSize,
    projectName: searchForm.projectName,
    subsidyStatus: searchForm.subsidyStatus,
  };

  // 处理时间范围
  if (
    searchForm.acceptanceTimeRange &&
    searchForm.acceptanceTimeRange.length === 2
  ) {
    queryParams.acceptanceTimeStart = searchForm.acceptanceTimeRange[0];
    queryParams.acceptanceTimeEnd = searchForm.acceptanceTimeRange[1];
  } else {
    queryParams.acceptanceTimeStart = "";
    queryParams.acceptanceTimeEnd = "";
  }

  loading.value = true;

  getPageSubsidyApplicationListApi(queryParams)
    .then((res) => {
      tableData.value = res.records || [];
      pagination.total = res.total || 0;
      pagination.current = res.current || 1;
      pagination.pageSize = res.size || 10;
    })
    .catch((error) => {
      console.error("查询补贴申请列表失败:", error);
      Message.error("查询失败，请稍后重试");
      tableData.value = [];
      pagination.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 查询数据列表
const search = () => {
  // 同步searchForm到queryParams
  queryParams.projectName = searchForm.projectName;
  queryParams.subsidyStatus = searchForm.subsidyStatus;

  // 处理时间范围
  if (
    searchForm.acceptanceTimeRange &&
    searchForm.acceptanceTimeRange.length === 2
  ) {
    queryParams.acceptanceTimeStart = searchForm.acceptanceTimeRange[0];
    queryParams.acceptanceTimeEnd = searchForm.acceptanceTimeRange[1];
  } else {
    queryParams.acceptanceTimeStart = "";
    queryParams.acceptanceTimeEnd = "";
  }

  loadData();
};

// 重置查询
const reset = () => {
  // 重置searchForm
  searchForm.projectName = "";
  searchForm.subsidyStatus = null;
  searchForm.acceptanceTimeRange = [];

  // 重置queryParams
  queryParams.projectName = "";
  queryParams.subsidyStatus = null;
  queryParams.acceptanceTimeStart = "";
  queryParams.acceptanceTimeEnd = "";
  queryParams.pageNum = 1;
  search();
};

// 分页变化
const handlePageChange = (page) => {
  queryParams.pageNum = page;
  search();
};

// 每页条数变化
const handlePageSizeChange = (pageSize) => {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  search();
};

// 新增补贴申请
const handleAdd = () => {
  currentSubsidyId.value = "";
  showEditPage.value = true;
  showProcessPage.value = false;
};

// 编辑补贴申请
const handleEdit = (row) => {
  currentSubsidyId.value = row.subsidyApplicationId;
  showEditPage.value = true;
  showProcessPage.value = false;
};

// 处理补贴申请
const handleProcess = (row) => {
  currentSubsidyId.value = row.subsidyApplicationId;
  showEditPage.value = false;
  showProcessPage.value = true;
};

// 编辑页面取消
const handleEditCancel = () => {
  showEditPage.value = false;
  currentSubsidyId.value = "";
};

// 编辑页面确认
const handleEditOk = () => {
  showEditPage.value = false;
  currentSubsidyId.value = "";
  // 刷新列表
  search();
};

// 处理页面取消
const handleProcessCancel = () => {
  showProcessPage.value = false;
  currentSubsidyId.value = "";
};

// 处理页面刷新
const handleProcessRefresh = () => {
  // 刷新列表
  search();
};

// 删除记录
const deleteRecord = (id) => {
  deleteLoading.value = true;

  deleteSubsidyApplicationBySubsidyApplicationIdApi(id)
    .then((res) => {
      Message.success("删除成功");
      search();
    })
    .catch((error) => {
      console.error("删除补贴申请失败:", error);
      Message.error("删除失败，请稍后重试");
    })
    .finally(() => {
      deleteLoading.value = false;
    });
};

// 初始化
onMounted(() => {
  search();
});
</script>
<style scoped>
.address-cell {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
  text-align: center;
  max-width: 100%;
  padding: 8px;
}
</style>
